package com.lq.memo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lq.email.entity.UserEmail;
import com.lq.email.mapper.UserEmailMapper;
import com.lq.memo.config.EmailSendConfig;
import com.lq.memo.service.UserEmailService;
import com.lq.memo.util.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: memo
 * @description:
 * @author: LQ
 * @create: 2021-11-24 11:05
 */
@Service
public class UserEmailServiceImpl implements UserEmailService {

    @Autowired
    IdWorker idWorker;

    @Autowired
    UserEmailMapper userEmailMapper;

    @Autowired
    EmailSendConfig emailSendConfig;

    @Override
    public void addUserEmail(UserEmail userEmail) {
        if (userEmail.getUseSystemEmailSend() == 1) {
            // 使用系统邮箱
            setSysSendEmail(userEmail);
        }
        if (StringUtils.isNotBlank(userEmail.getId())) {
            UserEmail queryUserEmail = userEmailMapper.selectById(userEmail.getId());
            if (queryUserEmail != null && StringUtils.isNotBlank(queryUserEmail.getId())) {
                // 已经存在数据,修改
                userEmailMapper.updateByPrimaryKey(userEmail);
                return;
            }
            userEmailMapper.insert(userEmail);
        }
        userEmail.setId(idWorker.nextIdStr());
        userEmailMapper.insert(userEmail);
    }

    @Override
    public UserEmail getUserEmail(UserEmail userEmail) {
        QueryWrapper<UserEmail> userEmailQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userEmail.getUserid())) {
            userEmailQueryWrapper.eq("userid", userEmail.getUserid());
        }
        List<UserEmail> userEmails = userEmailMapper.selectList(userEmailQueryWrapper);
        if (userEmails.size() > 0) {
            return userEmails.get(0);
        }
        return null;
    }

    /**
     * 设置系统发送邮箱
     *
     * @param userEmail
     */
    private void setSysSendEmail(UserEmail userEmail) {
        userEmail.setUseSystemEmailSend(1);
        userEmail.setEmaileSendForm(emailSendConfig.getEmailSendForm());
        userEmail.setEmailPassword(emailSendConfig.getEmailPassword());
        userEmail.setHost(emailSendConfig.getHost());
        userEmail.setPort(emailSendConfig.getPort());
        userEmail.setEncoding(emailSendConfig.getEncoding());
        userEmail.setSocketFactoryClass(emailSendConfig.getSocketFactoryClass());
        userEmail.setEmailType(emailSendConfig.getEmailType());
        userEmail.setEmailTypeName(emailSendConfig.getEmailTypeName());
    }
}
